import store from '@/store'

let webSock = null;
let global_callback = null;

const wsUri = "ws://localhost:9998/socket";

//初始化weosocket
function initWebSocket() {

    if (!webSock) {
        webSock = new WebSocket(wsUri);
        let username = sessionStorage.getItem("SET_NAME");
        if (username) {
            let agent = {
                "username": username,
                "topic": "login",
            }
            sendSock(agent);
        }
    }
    //ws地址
    webSock.onmessage = function (e) {
        websocketonmessage(e);
    }
    webSock.onclose = function (e) {
        console.log("连接关闭")
        websocketclose(e);
    }
    webSock.onopen = function () {
        websocketOpen();
    }
    //连接发生错误的回调方法
    webSock.onerror = function () {
        console.log("WebSocket连接发生错误");
    }
}

// 实际调用的方法
function sendSock(agentData, callback) {
    if (callback) {
        global_callback = callback;
    }
    if (webSock.readyState === webSock.OPEN) {
        //若是ws开启状态
        websocketsend(agentData)
    } else if (webSock.readyState === webSock.CONNECTING) {
        // 若是 正在开启状态，则等待1s后重新调用
        setTimeout(function () {
            sendSock(agentData, callback);
        }, 1000);
    } else {
        // 若未开启 ，则等待1s后重新调用
        setTimeout(function () {
            sendSock(agentData, callback);
        }, 1000);
    }
}



//关闭websocket
function webCloseWebsocket() {
    if (webSock) {
        webSock.close();
        webSock = ""
    }
}

//数据接收
function websocketonmessage(e) {
    console.log("数据接收。。。")
}

//数据发送
function websocketsend(agentData) {
    webSock.send(JSON.stringify(agentData));
}

//关闭
function websocketclose(e) {
    if (webSock) {
        webSock = null;
    }
    console.log("connection closed (" + e.code + ")");
}

function websocketOpen() {
    console.log("连接成功");
}


export {
    initWebSocket,
    sendSock,
    webCloseWebsocket
}